package labox.innovation.gameserver.timer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import labox.innovation.config.Config;
import labox.innovation.gameserver.GameTimeController;

/**
 * @author Administrator
 * 
 */
public final class Timer implements Comparable<Timer> {

	private static final Logger _log = LoggerFactory.getLogger(Timer.class.getName());

	private String name;

	private long _time;

	private long delay;

	boolean repeats;

	private Runnable doPostEvent;

	boolean isAlive;

	public Timer(long _delay, boolean _repeats, Runnable run) {
		delay = _delay / GameTimeController.MILLIS_IN_TICK;
		repeats = _repeats;
		doPostEvent = run;
	}

	public Timer(long _delay, String _name, boolean _repeats, Runnable run) {
		name = _name;
		delay = _delay / GameTimeController.MILLIS_IN_TICK;
		repeats = _repeats;
		doPostEvent = run;
	}

	public void cancel() {
		isAlive = false;
		TimerController.getInstance().removeTimer(this);
	}

	public void start() {
		if (isAlive)
			return;
		isAlive = true;
		putTimerTask();
	}

	void putTimerTask() {
		_time = GameTimeController.getGameTicks() + delay;
		TimerController.getInstance().addTimer(this);
	}

	public long getActiveTime() {
		return _time;
	}

	public void setDelay(long _delay) {
		delay = _delay / GameTimeController.MILLIS_IN_TICK;
	}

	public long getDelay() {
		return delay;
	}

	void post() {
		try {
			doPostEvent.run();
		} catch (Exception e) {
			_log.error("Timer runnable object invoke error", Config.SERVER_ID, e);
		}
		if (!repeats)
			isAlive = false;
	}

	public boolean isAlive() {
		return isAlive;
	}

	public boolean isRepeats() {
		return repeats;
	}

	public void setRepeats(boolean repeat) {
		repeats = repeat;
	}

	public String getName() {
		return name;
	}

	public int compareTo(Timer o) {
		return _time - o._time > 0 ? 1 : -1;
	}
}
